//useRef也能实现缓存
//能帮助你多次渲染时使用同一份数据(逃离useState的闭包)
//但需要注意改变useRef的对象的值 并不会自动触发更新

/* avoid re-creating the useRef() initial value.

function Image(props) {
  // ⚠️ IntersectionObserver is created on every render
  // 如果是个普通值应该就没撒问题
  const ref = useRef(new IntersectionObserver(onIntersect));
  // ...
}

// 改成↓

function Image(props) {
  const ref = useRef(null);

  // ✅ IntersectionObserver is created lazily once
  function getObserver() {
    if (ref.current === null) {
      ref.current = new IntersectionObserver(onIntersect);
    }
    return ref.current;
  }

  // When you need it, call getObserver()
  // ...
}
*/

import React, {useEffect, useRef} from 'react';

class Person {
  constructor(public name: string, public age: number) {
    console.log('Person 构造器执行中');
  }
}

export default function () {
  /** emmm endanger里说这个initialValue每次都会重新执行,但经过测试,貌似并不会 (16.12.0)
   * https://reactjs.org/docs/hooks-faq.html#how-to-create-expensive-objects-lazily*/
  const ref = useRef(new Person('ahhh', 123));

  useEffect(() => {
    setInterval(() => {
      console.log(JSON.stringify(ref.current));
    }, 1500);
  }, [])

  return (
    <div>
      <button onClick={() => ref.current.name = 'ahhh2'}>change</button>
    </div>
  );
};
